<template>
  <div class="cart-page">
    <!-- 购物车主体内容 -->
    <div class="cart-content">
      <!-- 左侧商品列表 -->
      <div class="cart-items">
        <div class="cart-tab">
          <el-tabs v-model="activeTab" @tab-click="handleTabClick">
            <el-tab-pane :label="$t('优惠券')" :name="0"></el-tab-pane>
            <el-tab-pane :label="$t('秒杀优惠券')" :name="1"></el-tab-pane>
          </el-tabs>
        </div>
        <div class="cart-header">
          <h2>{{ $t('购物车') }} <span class="item-count">({{ totalNum }}{{ $t('件商品') }})</span></h2>
          <el-button v-if="totalNum > 0" type="text" @click="removeItem()">{{ $t('清空购物车') }}</el-button>
        </div>

        <div class="items-list">
          <div v-if="totalNum > 0" class="item-all">
            <el-checkbox v-model="checkedAll" :indeterminate="isIndeterminate" :label="$t('全选')" size="large" @change="toggleSelectAll" />
          </div>
          <el-empty v-if="totalNum <= 0" :description="$t('暂无商品')" />
          <div v-for="item in cartItems" :key="item.id" class="cart-item">
            <el-checkbox v-model="item.selected"></el-checkbox>
            <div class="item-image">
              <img :src="item.productImg" :alt="item.productName">
            </div>
            <div class="item-info">
              <div class="item-title">{{ item.productName }}</div>
              <div class="item-price">
                <span class="currency">{{ langStore.languageSymbol }}</span>
                <span class="amount">{{ item.productPrice * langStore.languageRate }}</span>
              </div>
<!--              <div class="item-stock" :class="{ 'low-stock': item.stock < 5 }">-->
<!--                {{ item.stock > 0 ? `库存：${item.stock}件` : '暂时缺货' }}-->
<!--              </div>-->
              <div class="item-actions">
                <div class="quantity-control">
                  <button
                    class="quantity-btn minus"
                    @click="updateQuantity(item, -1)"
                    :disabled="item.productNum <= 1"
                  >
                    <i class="fas fa-minus"></i>
                  </button>
                  <input
                    type="number"
                    class="quantity-input"
                    v-model.number="item.productNum"
                    min="1"
                    :max="item.stock"
                    @change="handleQuantityChange(item)"
                  >
                  <button
                    class="quantity-btn plus"
                    @click="updateQuantity(item, 1)"
                    :disabled="item.productNum >= item.stock"
                  >
                    <i class="fas fa-plus"></i>
                  </button>
                </div>
                <el-button type="text" @click="removeItem(item.id)">{{ $t('删除') }}</el-button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧结算区域 -->
      <div class="cart-summary">
        <div class="summary-card">
          <div class="total-section">
            <div class="subtotal">
              <span>{{ $t('商品总价') }}：</span>
              <span class="amount">
                <span class="currency">{{ langStore.languageSymbol }}</span>
                {{ getcalculateTotal }}
              </span>
            </div>
            <div class="shipping">
              <span>{{ $t('运费') }}：</span>
              <span class="free">{{ $t('免费') }}</span>
            </div>
          </div>

          <div class="checkout-total">
            <span>{{ $t('会员等级') }}：</span>
            <span class="final-price">
              <span class="currency">{{ langStore.languageSymbol }}</span>
              {{ userStore.userInfo.member.userVipLevel }}
            </span>
          </div>
          <div class="checkout-total">
            <span>{{ $t('折扣') }}：</span>
            <span class="final-price">
              <span class="currency">{{ langStore.languageSymbol }}</span>
              {{ (userStore.userInfo.member.userVipLevelRate || 0)*100}}%
            </span>
          </div>
          <div class="checkout-total">
            <span>{{ $t('结算金额') }}：</span>
            <span class="final-price">
              <span class="currency">{{ langStore.languageSymbol }}</span>
              {{ calculateTotal() }}
            </span>
          </div>

          <el-button
            type="primary"
            class="checkout-button"
            :disabled="!hasSelectedItems"
            @click="goToCheckout"
          >
            {{ $t('结算') }} ({{ getSelectedCount() }}{{ $t('件') }})
          </el-button>

          <div class="prime-promotion" v-if="!isPrimeMember">
            <div class="prime-tag">PRIME</div>
            <div class="prime-info">
              <div class="prime-title">{{ $t('免费试用 Prime 会员') }}</div>
              <div class="prime-benefits">{{ $t('享受免费次日达和 Prime 会员专享折扣') }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed , onMounted } from 'vue'
import { useRouter } from 'vue-router'
import {ElLoading, ElMessage, ElMessageBox} from 'element-plus'
import {ApiCartList, ApiDeleteCart, ApiUpdateCartNum} from "@/api/commodity.js";
import {debounce} from "@/utils/utils.js";
import useLangStore from '@/store/modules/lang'
import useCartStore from "@/store/modules/cart.js";
import {multiplication,_sub} from '@/utils/utils.js'
const langStore = useLangStore()
const cartStore = useCartStore();

import {useI18n} from "vue-i18n";
const { t } = useI18n();
const router = useRouter()
import useUserStore from '@/store/modules/user'

const userStore = useUserStore();

//折扣率
const isPrimeMember = ref(false)

// 模拟购物车数据
const cartItems = ref([])
const totalNum = ref(0)

const getCartList = () => {
  const loadingInstance = ElLoading.service()
  ApiCartList({
    pageNum: 1,
    pageSize: 99999,
    type: activeTab.value
  }).then(res => {
    cartItems.value = res.rows
    totalNum.value = res.total
  }).finally(() => {
    loadingInstance.close()
  })
}

// 购物车全选
const checkedAll = ref(false)
const isIndeterminate = computed(() => {
  checkedAll.value = cartItems.value.every(item => item.selected)
  return cartItems.value.some(item => !item.selected) && cartItems.value.some(item => item.selected)
})
const toggleSelectAll = () => {
  cartItems.value.forEach(item => {
    item.selected = checkedAll.value
  })
  updateCart()
}

// tab
const activeTab = ref(0)
const handleTabClick = () => {
  checkedAll.value = false
  getCartList()
}
const getcalculateTotal = computed(() => {
  if((userStore.userInfo.member.userVipLevelRate || 0) != 0){
    let sun =(cartItems.value.filter(item => item.selected).reduce((total, item) => total + item.productPrice * langStore.languageRate * item.productNum, 0).toFixed(2));
    return sun;
  }else{
    console.log('走的则立22222222222');
    return cartItems.value
    .filter(item => item.selected)
    .reduce((total, item) => total + item.productPrice * langStore.languageRate * item.productNum, 0)
    .toFixed(2)
  }
})
// 计算总价
const calculateTotal = () => {
  if((userStore.userInfo.member.userVipLevelRate || 0) != 0){
    let sun =(cartItems.value.filter(item => item.selected).reduce((total, item) => total + item.productPrice * langStore.languageRate * item.productNum, 0).toFixed(2));
    let userVipLevelRate = 1-userStore.userInfo.member.userVipLevelRate
    sun  =  multiplication(Number(sun),Number(userVipLevelRate))
    
    return sun;
  }else{
    console.log('走的则立22222222222');
    return cartItems.value
    .filter(item => item.selected)
    .reduce((total, item) => total + item.productPrice * langStore.languageRate * item.productNum, 0)
    .toFixed(2)
  }

}

// 获取选中商品数量
const getSelectedCount = () => {
  return cartItems.value.filter(item => item.selected).length
}

// 是否有选中的商品
const hasSelectedItems = computed(() => {
  return cartItems.value.some(item => item.selected)
})

// 删除商品
const removeItem = (id) => {
  if(id) {
    ApiDeleteCart({
      shopCartIds: [id]
    }).then(() => {
      checkedAll.value = false
      getCartList()
      cartStore.getCartList()
    })
  } else {
    ElMessageBox.confirm(t('确定要清空购物车吗？'), t('提示'), {
      confirmButtonText: t('确定'),
      cancelButtonText: t('取消'),
      type: 'warning'
    }).then(() => {
      ApiDeleteCart({
        shopCartIds: cartItems.value.map(item => item.id)
      }).then(() => {
        checkedAll.value = false
        getCartList()
        cartStore.getCartList()
      })
    })
  }
}

// 跳转到结算页面
const goToCheckout = () => {
  const cartIds = cartItems.value.filter(item => item.selected).map(item => item.id)
  router.push({
    path: '/products/checkout',
    query: {
      cartIds: cartIds.toString()
    }
  })
}

const updateQuantity = (item, delta) => {
  const newQuantity = item.productNum + delta
  if (newQuantity < 1) {
    ElMessage({
      message: t('商品数量不能小于1'),
      type: 'warning',
      duration: 2000
    })
    return
  }
  if (newQuantity > item.stock) {
    ElMessage({
      message: `${t('当前商品库存仅剩')} ${item.stock} ${t('件')}`,
      type: 'warning',
      duration: 2000
    })
    return
  }
  item.productNum = newQuantity
  updateCart();
  debounce(() => {
    ApiUpdateCartNum({
      shopCartId: item.id,
      productNum: item.productNum
    })
  })
}

const handleQuantityChange = (item) => {
  if (isNaN(item.productNum) || item.productNum < 1) {
    item.productNum = 1
    ElMessage({
      message: t('商品数量不能小于1'),
      type: 'warning',
      duration: 2000
    })
  } else if (item.productNum > item.stock) {
    item.productNum = item.stock
    ElMessage({
      message: `${t('当前商品库存仅剩')} ${item.stock} ${t('件')}`,
      type: 'warning',
      duration: 2000
    })
  }
  // 确保数量为整数
  item.productNum = Math.floor(item.productNum)
  updateCart()
  debounce(() => {
    ApiUpdateCartNum({
      shopCartId: item.id,
      productNum: item.productNum
    })
  })
}

const updateCart = () => {
  calculateTotal()
}

onMounted(() => {
  getCartList()
})
</script>

<style lang="scss" scoped>
@import '@/styles/variables.scss';

.cart-page {
  padding: 0 20px;
  background: $bg-white;

  @media (max-width: 768px) {
    padding: 0;
  }

  .cart-content {
    display: grid;
    grid-template-columns: 1fr 320px;
    gap: 20px;
    max-width: $max-width;
    margin: 0 auto;

    @media (max-width: 768px) {
      grid-template-columns: 1fr;
      gap: 12px;
    }

    .cart-items {
      background: $bg-white;
      border-radius: $border-radius-md;

      @media (max-width: 768px) {
        border-radius: 0;
      }

      .cart-tab{
        width: 100%;
      }

      .cart-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;

        h2 {
          font-size: $font-size-xl;
          font-weight: $font-weight-medium;
          color: $amazon-text-primary;

          .item-count {
            color: $amazon-text-secondary;
            font-size: $font-size-base;
            font-weight: $font-weight-normal;
          }
        }
      }

      .item-all{
        border-bottom: 1px solid #D5D9D9;
      }
      .cart-item {
        display: flex;
        align-items: flex-start;
        padding: 20px 0;
        border-bottom: 1px solid $amazon-border;

        @media (max-width: 768px) {
          padding: 12px 0;
          flex-direction: column;

          .item-image {
            width: 100%;
            height: auto;
            margin: 0 0 12px;
          }

          .item-info {
            width: 100%;

            .item-actions {
              flex-wrap: wrap;
              justify-content: space-between;
            }
          }
        }

        .item-image {
          width: 120px;
          height: 120px;
          margin: 0 20px;
          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            border-radius: $border-radius-sm;
          }
        }

        .item-info {
          flex: 1;

          .item-title {
            font-size: $font-size-base;
            color: $amazon-text-primary;
            margin-bottom: 10px;
          }

          .item-price {
            color: $amazon-text-primary;
            margin-bottom: 8px;

            .currency {
              font-size: $font-size-sm;
            }

            .amount {
              font-size: $font-size-lg;
              font-weight: $font-weight-medium;
            }
          }

          .item-stock {
            font-size: $font-size-sm;
            color: $amazon-success;
            margin-bottom: 10px;

            &.low-stock {
              color: $amazon-error;
            }
          }

          .item-actions {
            display: flex;
            align-items: center;
            gap: 15px;

            .quantity-control {
              display: flex;
              align-items: center;
              border: 1px solid #ddd;
              border-radius: 4px;
              width: fit-content;
            }

            .quantity-btn {
              width: 32px;
              height: 32px;
              border: none;
              background: #f5f5f5;
              cursor: pointer;
              display: flex;
              align-items: center;
              justify-content: center;
              transition: all 0.2s;
            }

            .quantity-btn.minus {
              border-right: 1px solid #ddd;
              border-top-left-radius: 4px;
              border-bottom-left-radius: 4px;
            }

            .quantity-btn.plus {
              border-left: 1px solid #ddd;
              border-top-right-radius: 4px;
              border-bottom-right-radius: 4px;
            }

            .quantity-btn:hover:not(:disabled) {
              background: #e6e6e6;
            }

            .quantity-btn:disabled {
              cursor: not-allowed;
              opacity: 0.5;
            }

            .quantity-btn i {
              font-size: 12px;
              color: #333;
            }

            .quantity-input {
              width: 45px;
              height: 32px;
              border: none;
              text-align: center;
              font-size: 14px;
              color: #333;
              appearance: textfield;
              -moz-appearance: textfield;
              -webkit-appearance: none;
            }

            .quantity-input::-webkit-outer-spin-button,
            .quantity-input::-webkit-inner-spin-button {
              -webkit-appearance: none;
              margin: 0;
            }

            .quantity-input:focus {
              outline: none;
            }

            :deep(.el-button--text) {
              color: $amazon-link;

              &:hover {
                color: $amazon-link-hover;
              }
            }
          }
        }
      }
    }

    .cart-summary {
      @media (max-width: 768px) {
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        z-index: 100;
        background: $bg-white;
        box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);

        .summary-card {
          border: none;
          border-radius: 0;
          padding: 12px;

          .total-section {
            display: none;
          }

          .checkout-total {
            margin: 0 0 5px;
            padding: 0;
          }

          .prime-promotion {
            display: none;
          }
        }
      }

      .summary-card {
        background: $bg-white;
        border-radius: $border-radius-md;
        padding: 20px;
        border: 1px solid $amazon-border;

        .total-section {
          margin-bottom: 15px;

          .subtotal, .shipping {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;
            font-size: $font-size-sm;
            color: $amazon-text-secondary;

            .amount {
              color: $amazon-text-primary;
              font-weight: $font-weight-medium;
            }

            .free {
              color: $amazon-success;
            }
          }
        }

        .checkout-total {
          display: flex;
          justify-content: space-between;
          align-items: baseline;
          margin: 10px 0;
          padding-top: 10px;
          border-top: 1px solid $amazon-border;
          font-size: $font-size-lg;
          color: $amazon-text-primary;

          .final-price {
            font-size: $font-size-2xl;
            font-weight: $font-weight-medium;

            .currency {
              font-size: $font-size-base;
            }
          }
        }

        .checkout-button {
          width: 100%;
          height: 40px;
          margin: 10px 0;
          background: $amazon-yellow;
          border-color: $amazon-yellow-border;
          color: $amazon-text-primary;
          font-size: 16px;

          &:hover {
            background: $amazon-yellow-hover;
          }

          &:disabled {
            background: $amazon-background-light;
            border-color: $amazon-border;
            color: $amazon-text-secondary;
          }
        }

        .prime-promotion {
          margin-top: 20px;
          padding: 15px;
          background: $amazon-background-light;
          border-radius: $border-radius-md;
          display: flex;
          align-items: center;
          gap: 12px;

          .prime-tag {
            background: $amazon-prime;
            color: $text-white;
            padding: 2px 8px;
            border-radius: 2px;
            font-size: 12px;
            font-weight: 500;
          }

          .prime-info {
            .prime-title {
              font-size: $font-size-sm;
              font-weight: $font-weight-medium;
              color: $amazon-text-primary;
              margin-bottom: 4px;
            }

            .prime-benefits {
              font-size: $font-size-xs;
              color: $amazon-text-secondary;
            }
          }
        }
      }
    }
  }
}

.quantity-control {
  .quantity-input {
    &:disabled {
      background-color: #f5f5f5;
      cursor: not-allowed;
    }
  }
}

.low-stock {
  .quantity-control {
    border-color: $amazon-error;

    .quantity-input {
      color: $amazon-error;
    }
  }
}
</style>
